<template>
  <div class="com-container">
    <div ref="chart" class="com-chart"></div>
  </div>
</template>

<script>
import { markRaw } from 'vue';
import * as echarts from 'echarts'
// import chalk from '@/assets/theme/chalk'
require('echarts/theme/dark');
export default {
  data() {
    return {
      chartInstance: null,
      allData: null,  // 服务器返回的数据
      currentPage: 1,  // 当前页数
      totalPage: 0,  // 一共多少页
      timeId: null
    }
  },
  mounted() {
    this.initChart()
    this.getData()
    window.addEventListener('resize', this.screenAdapter)
    this.screenAdapter()
  },
  destroyed() {
    clearInterval(this.timeId)
    window.removeEventListener('resize', this.screenAdapter)
  },
  methods: {
    // 初始化chartInstance的对象
    initChart() {
      // echarts.registerTheme("chalk", chalk)
      this.chartInstance = markRaw(echarts.init(this.$refs.chart,'dark'))
      const initOption = {
        title: {
          text: '▎职业与睡眠时长条形图',
          left: 8,
          top: 8
        },
        grid: {
          top: '20%',
          left: '3%',
          right: '6%',
          bottom: '3%',
          containLabel: true // 距离是包含坐标轴上的文字
        },
        xAxis: {
          type: 'value',
          min: 7.1,
          max: 7.16,
          axisLine: {
            show: true, // 显示坐标轴线
            lineStyle: {
              type: 'solid' // 坐标轴线的类型，可以是 'solid', 'dashed', 'dotted'
            }
          },
          splitLine: {
            show: false,
            lineStyle: {
              type: 'dashed',
            },
          },
        },
        yAxis: {
          type: 'category',
          axisTick:{
            show: false
          }
        },
        series: [
          {
            type: 'bar',
            label: {
              show: true,
              position: 'right',
              textStyle: {
                color: 'white'
              }
            },
            itemStyle: {
              // 指明颜色渐变的方向
              // 指明不同百分比之下颜色的值
              color: new echarts.graphic.LinearGradient(0, 0, 1, 0, [
                // 百分之0状态之下的颜色值
                {
                  offset: 0,
                  color: '#5052EE'
                },
                // 百分之100状态之下的颜色值
                {
                  offset: 1,
                  color: '#AB6EE5'
                }
              ])
            }
          }
        ]
      }
      this.chartInstance.setOption(initOption)
    },
    // 获取服务器数据
    async getData() {
      const { data: ret } = await this.$axios.get('chart1')
      this.allData = ret

      // 组合 occupation 和 avg_sleep_duration 为一个数组
      const combinedData = this.allData.occupation.map((occupation, index) => ({
        occupation: occupation,
        avg_sleep_duration: this.allData.avg_sleep_duration[index]
      }));
      // 对组合后的数组进行排序
      combinedData.sort((a, b) => a.avg_sleep_duration - b.avg_sleep_duration);
      // 分解排序后的数组
      this.allData.occupation = combinedData.map(item => item.occupation);
      this.allData.avg_sleep_duration = combinedData.map(item => item.avg_sleep_duration);

      this.totalPage = Math.ceil(this.allData.occupation.length / 4);
      this.updataChart()
      this.startInterval()
    },
    // 更新图表数据
    updataChart() {
      const start = (this.currentPage - 1) * 4
      const end = this.currentPage * 4
      const occupationName = this.allData.occupation.slice(start, end)
      const sleepDurationName = this.allData.avg_sleep_duration.slice(start, end)
      const dataOption = {
        yAxis: {
          data: occupationName,
        },
        series: [
          {
            type: 'bar', 
            data: sleepDurationName,
          }
        ]
      }
      this.chartInstance.setOption(dataOption)
    },
    startInterval() {
      if (this.timeId) {
        clearInterval(this.timeId)
      }
      this.timeId = setInterval(() => {
        this.currentPage++
        if (this.currentPage > this.totalPage) {
          this.currentPage = 1
        }
        this.updataChart()
      }, 3000)
    },
    screenAdapter() {
      const titleFontSize = this.$refs.chart.offsetWidth / 100 * 4
      const fontSize = this.$refs.chart.offsetWidth / 100 * 6.18
      const adapterOption = {
        title: {
          textStyle: {
            fontSize: titleFontSize
          }
        },
        series: [
          {
            barWidth: fontSize,
            itemStyle: {
              borderRadius: [0, fontSize / 2, fontSize / 2, 0],
            }
          }
        ]
      }
      this.chartInstance.setOption(adapterOption)
      this.chartInstance.resize()
    }
  }

}
</script>

<style scoped>
</style>